<?php


namespace App\Http\Controllers\Api\V1\Manager;


use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\CheckRecord;
use App\Models\Record;
use App\Models\RecordType;
use App\Models\User;
use App\Services\Front\HealthService;
use App\Services\Front\IdcardService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class RecordController extends Controller
{
    public function index(Request $request)
    {
        $pageSize = $request->pageSize;
        $userName = $request->userName;
        $phone = $request->phone;
        $status = $request->status;
        $categoryName = $request->categoryName;
        $managerId = $request->MANAGERID;
        $excel = $request->excel;
        $sql =  Record::select('t1.*', 't2.categoryName','t3.recordType')
            ->from((new Record())->getTable() . ' as t1')
                ->join((new Category())->getTable() . ' as t2', 't1.categoryId', '=', 't2.categoryId')
                ->join((new RecordType())->getTable() . ' as t3', 't2.recordTypeId', '=', 't3.recordTypeId')
                ->leftJoin((new User())->getTable() . ' as t4', 't1.idCard', '=', 't4.idCard');
        if($userName){
            $sql->where('t1.userName','like','%'.$userName.'%');
        }
        if($phone){
            $sql->where('t1.phone','like','%'.$phone.'%');
        }
        if($categoryName){
            $sql->where('t2.categoryName','like','%'.$categoryName.'%');
        }
        if(isset($status)){
            $sql->where('t1.status',$status);
        }
//        if ($managerId != 1) {
//            $sql->where('t4.managerId', $managerId);
//        }
        $sql->groupBy('t1.recordId');
        if($excel){
            $data = $sql->orderBy('t1.createTime', 'desc')->get()->toArray();
            $result = [['种类', '分类', '姓名', '身份证号', '手机号', '送检人', '送检单位', '送检时间', '上传时间', '状态'],];
            $i = 0;
            foreach ($data as $value) {
                $status = str_replace([0,1,2],['待审核','正确','错误'],$value['status']);
                $result[$i + 1] = [$value['categoryName'], $value['recordType'],$value['userName'] . "'", $value['idCard'] . "'", $value['phone'],
                    $value['submitName'], $value['submitUnit'], $value['submitTime'], $value['createTime'],$status];
                $i++;
            }
            $status = Excel::create("记录", function ($excel) use ($result) {
                $excel->sheet('record', function ($sheet) use ($result) {
                    $sheet->setFontFamily('宋体');
                    $sheet->rows($result);

                });
            });
            return $status->export('xls');
        }
        $data =$sql->orderByDesc('t1.createTime')->paginate($pageSize)->toArray();
        $result['recordList'] = $data['data'];
        $result['totalNum'] = $data['total'];
        return $this->apiResponse($result);
    }
    public function show($recordId)
    {
       $data =  Record::select('t1.*', 't2.categoryName','t3.recordType')
           ->from((new Record())->getTable() . ' as t1')
           ->join((new Category())->getTable() . ' as t2', 't1.categoryId', '=', 't2.categoryId')
           ->join((new RecordType())->getTable() . ' as t3', 't2.recordTypeId', '=', 't3.recordTypeId')
            ->where('t1.recordId',$recordId)->first();
       return $this->apiResponse($data);
    }
    public function store(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            "categoryId" => "integer|required",
            "submitTime" => "required",
            "userName" => "required",
            "idCard" => "required",
            "phone" => "required",
            "submitUnit" => "required",
            "submitName" => "required",
        ]);
        if ($validator->fails()) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $status = IdcardService::idcardStatus($data['idCard'], $data['userName']);
        if (!$status) {
            return $this->apiResponse('', config('errorCode.NAME_ERROR'));
        }
        if($data['recordId']){
            Record::where('recordId',$data['recordId'])->update($data);
        }else{
            $data['createTime'] = date('Y-m-d H:i:s');
            Record::create($data);
        }
        return $this->apiResponse(true);
    }
    public function destroy($recordId)
    {
        Record::destroy($recordId);
        CheckRecord::where('recordId',$recordId)->delete();
        return $this->apiResponse(true);
    }

    public function checkRecord(Request $request)
    {
        $recordId = $request->recordId;
        $record = Record::find($recordId);

        $data = Category::where('parentId',$record['categoryId'])->orderBy('sort')->get()->toArray();
     //  dd($record);
        foreach ($data as &$value){
            $value['imageList'] = CheckRecord::where(['categoryId'=>$value['categoryId'],'recordId'=>$recordId])->orderBy('sort')->get()->toArray();
            $value['imageNum'] = count($value['imageList']);
        }
        return $this->apiResponse($data);
    }
    public function addCheckRecord(Request $request)
    {
        $recordId = $request->recordId;
        $categoryId = $request->categoryId;
        $urlList = $request->urlList;
        CheckRecord::where(['categoryId'=>$categoryId,'recordId'=>$recordId])->delete();
        foreach ($urlList as $key=>$value){
            CheckRecord::create(['categoryId'=>$categoryId,'recordId'=>$recordId,'url'=>$value,'sort'=>$key]);
        }
        Record::where('recordId',$recordId)->update(['status'=>0]);
        return $this->apiResponse(true);
    }

    public function updateStatus(Request $request)
    {
        $recordId = $request->recordId;
        $status = $request->status;
        if (!$recordId || !$status) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        Record::where('recordId',$recordId)->update(['status'=>$status]);
        if($status == 1){
            $record = Record::find($recordId);
            $user = User::where(['idCard'=>$record['idCard'],'userName'=>$record['userName']])->first();
            if($user){
                HealthService::addRecordNotice($user['userId']);
            }
        }
        return $this->apiResponse(true);
    }
}